package io.adrainty.bolee.framework.gateway.filter;

import cn.hutool.core.lang.Snowflake;
import io.adrainty.bolee.framework.gateway.decorator.CacheServerHttpResponseDecorator;
import io.adrainty.bolee.framework.gateway.properties.LogRecordProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/28 上午12:53
 */

@Slf4j
@Component
public class ResponseRecordFilter extends BaseFilter {

    @Value("${spring.application.name}")
    private String applicationName;

    private final LogRecordProperties properties;

    private final StreamBridge streamBridge;

    private final Snowflake snowflake;

    public ResponseRecordFilter(
            @Autowired LogRecordProperties properties,
            @Autowired StreamBridge streamBridge,
            @Autowired Snowflake snowflake
    ) {
        this.properties = properties;
        this.streamBridge = streamBridge;
        this.snowflake = snowflake;
    }

    @Override
    protected Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
        CacheServerHttpResponseDecorator decorator = new CacheServerHttpResponseDecorator(
                streamBridge,
                snowflake.nextId(),
                applicationName,
                exchange
        );
        // 把当前的应答体进行改变，用于传递新放入的response中
        return chain.filter(exchange.mutate().response(decorator).build());
    }

    @Override
    protected boolean isFilter(String path, boolean isUploadRequest, ServerHttpRequest request) {
        if (isUploadRequest) return false;
        return nonePathMatch(properties.getIgnoreUrl(), path);
    }

    @Override
    public int getOrder() {
        return -2;
    }

}
